<?php


namespace PKApp\Content;

use PKApp\Content\Classes\TraitContent;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Numbers;
use PKFrame\DataHandler\Pages;
use PKFrame\DataHandler\Str;

class AdminPage extends AdminController
{
    use TraitContent;

    public function Main()
    {
        $this->assign([
            'id' => Numbers::To(request()->get('id'))
        ])->fetch('page_editor');
    }

    public function ApiGetDetail()
    {
        $this->json(
            $this->serviceOfPage()->interface_getEntityById(
                request()->get('id')
            )
        );
    }

    protected function model(): array
    {
        $post = $this->checkModel(['title', 'content']);
        $post['title'] = Str::strCutOfTinytext($this->checkPostFieldIsEmpty('title', 'Content_titleEmpty'));
        $post['siteId'] = $this->loginUser()->SiteId;
        // 检查单页面的SEO编辑权限
        if (in_array('changeCategorySEOPower', $this->loginUser()->PowerByAction)) {
            $seo = $this->checkModel(['seoTitle', 'seoKeywords', 'seoDescription']);
            !empty($seo['seoTitle']) ? $seo['seoTitle'] = Str::strCutOfTinytext($seo['seoTitle']) : $seo['seoTitle'] = $post['title'];
            $post = array_merge($post, $seo);
        }
        $post['seoKeywords'] = Str::strCutOfTinytext($post['seoKeywords']);
        return $post;
    }

    public function ApiByChange()
    {
        $id = $this->checkPostFieldIsEmpty('id', 'Category_idEmpty');
        $post = $this->model();
        $imgList = Pages::GetImgsInArticle(htmlspecialchars_decode($post['content']));
        if (Arrays::Is($imgList)) {
            foreach ($imgList as $index => $item_img) {
                $img_arr = parse_url($item_img);
                count($img_arr) == 1 ?: $post['content'] = str_replace($item_img, '/' . ltrim($img_arr['path'], '/'), $post['content']);
            }
        }
        $service = $this->serviceOfPage();
        $pageEntity = $service->GetEntity(['id' => $id]);
        if (Arrays::Is($pageEntity)) {
            $service->UpdateById($id, $post);
        } else {
            $service->Add($post);
        }
        $this->inputSuccess();
    }

}